from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin

from apps.system.models import SystemRole


class SystemUserManager(BaseUserManager):

	def _create_user(self, username, password, **kwargs):
		if not username:
			raise ValueError("请输入用户名")
		if not password:
			raise ValueError("请输入密码")
		user = self.model(username=username, **kwargs)
		user.set_password(password)
		user.save()
		return user

	def create_user(self, username, mobile, email, password, **kwargs):
		if not mobile:
			raise ValueError("请输入手机号")
		if not email:
			raise ValueError("请输入邮箱地址")
		user = self._create_user(username=username, mobile=mobile, email=email, password=password, **kwargs)

	def create_superuser(self, username, password, **kwargs):
		kwargs['is_superuser'] = True
		kwargs['is_staff'] = True
		self._create_user(username=username, password=password, **kwargs)


class SystemUser(AbstractBaseUser, PermissionsMixin):
	username = models.CharField(max_length=50, unique=True, verbose_name="用户名")
	mobile = models.CharField(max_length=11, verbose_name="手机号")
	email = models.EmailField(null=True, verbose_name="用户邮箱")
	password = models.CharField(max_length=128)
	nick_name = models.CharField(max_length=50, null=True, verbose_name="用户昵称")
	is_staff = models.BooleanField(default=False)
	is_superuser = models.BooleanField(default=False)
	# role = models.IntegerField(null=True, verbose_name="用户权限")
	role = models.ForeignKey(SystemRole, related_name='role', on_delete=models.DO_NOTHING, verbose_name="用户权限")
	status = models.BooleanField(default=True)
	create_time = models.DateTimeField(auto_now_add=True)
	update_time = models.DateTimeField(auto_now=True)
	last_login = models.DateTimeField(blank=True, null=True)
	deleted = models.BooleanField(default=False)

	objects = SystemUserManager()

	USERNAME_FIELD = "username"
	EMAIL_FIELD = 'email'

	class Meta:
		db_table = 'tiresias_sys_user'
		verbose_name = "系统用户"
		verbose_name_plural = verbose_name

	def __str__(self):
		return self.get_username()
